<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约时间" prop="appDateTime">
        <el-date-picker clearable
                        v-model="queryParams.appDateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['LXHappointment:LXHDOCappointment:add']"
        >新增预约就诊</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['LXHappointment:LXHDOCappointment:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['LXHappointment:LXHDOCappointment:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['LXHappointment:LXHDOCappointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="LXHDOCappointmentList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="预约Id" align="center" prop="appId" /> -->
<!--      <el-table-column label="用户id" align="center" prop="userId" />-->
<!--      <el-table-column label="用户名字" align="center" prop="userName" /> &lt;!&ndash; 新增 &ndash;&gt;-->
<!--      <el-table-column label="医生id" align="center" prop="doctorId" />-->
      <el-table-column label="医生名字" align="center" prop="doctorName" />
      <el-table-column label="预约描述" align="center" prop="appInfo" />
      <el-table-column label="预约时间" align="center" prop="appDateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appDateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约地址" align="center" prop="appAddress" />

      <!-- 新增：诊断描述列 -->
      <el-table-column label="诊断描述" align="center" prop="treatInfo" />

      <!-- 新增：诊断状态列（有颜色显示） -->
      <el-table-column label="诊断状态" align="center" prop="treatState">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.treatState)">{{ scope.row.treatState }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['LXHappointment:LXHDOCappointment:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改个人预约就诊对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="LXHDOCappointmentRef" :model="form" :rules="rules" label-width="80px">
        <!-- 新增医生选择下拉框 -->
        <el-form-item label="医生" prop="doctorId">
          <el-select
              v-model="form.doctorId"
              placeholder="请选择医生"
              clearable
              remote
              :remote-method="loadDoctors"
              :loading="doctorLoading"
          >
            <el-option
                v-for="doctor in doctorOptions"
                :key="doctor.doctorId"
                :label="doctor.doctorName"
                :value="doctor.doctorId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预约描述" prop="appInfo">
          <el-input v-model="form.appInfo" placeholder="请输入预约描述" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appDateTime">
          <el-date-picker clearable
                          v-model="form.appDateTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="提交时间" prop="appCreate">
          <el-date-picker clearable
            v-model="form.appCreate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择提交时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="预约地址" prop="appAddress">
          <el-input v-model="form.appAddress" placeholder="请输入预约地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LXHDOCappointment">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listLXHDOCappointment, getLXHDOCappointment, delLXHDOCappointment, addLXHDOCappointment, updateLXHDOCappointment } from "@/api/LXHappointment/LXHDOCappointment"
import { getDoctorList } from "@/api/LXHappointment/doctor" // 引入医生列表接口，需提前封装好该接口

const { proxy } = getCurrentInstance()

// 表格数据相关
const LXHDOCappointmentList = ref([])
const loading = ref(true)
const total = ref(0)

// 弹窗相关
const open = ref(false)
const title = ref("")



// 根据诊断状态获取对应的 el-tag 类型（颜色）
const getTagType = (state) => {
  if (state === '待就诊') {
    return 'warning'; // 橙色
  } else if (state === '已就诊') {
    return 'success'; // 绿色
  } else if (state === '已完成') {
    return 'success'; // 绿色，也可根据需求调整
  } else {
    return ''; // 无类型，默认灰色
  }
};


// 医生选择相关
const doctorOptions = ref([])
const doctorLoading = ref(false)

// 选择器相关（已注释删除功能，保留基础逻辑）
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)




// 表单数据与查询参数
const data = reactive({
  form: {
    appId: null,
    userId: null,
    doctorId: null,
    appInfo: null,
    appDateTime: null,
    appCreate: null,
    appStatse: null,
    appAddress: null,
    // 新增字段：诊断描述和状态（用于接收后端返回数据）
    treatInfo: null,
    treatState: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appDateTime: null,
  },
  rules: {
    doctorId: [
      { required: true, message: "医生不能为空", trigger: "change" }
    ],
    appInfo: [
      { required: true, message: "预约描述不能为空", trigger: "blur" }
    ],
    appDateTime: [
      { required: true, message: "预约时间不能为空", trigger: "blur" }
    ],
    appAddress: [
      { required: true, message: "预约地址不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询个人预约就诊列表 */
function getList() {
  loading.value = true
  listLXHDOCappointment(queryParams.value)
      .then(response => {
        LXHDOCappointmentList.value = response.rows || []
        total.value = response.total || 0
      })
      .catch(error => {
        ElMessage.error("查询失败，请重试")
        console.error("列表查询错误:", error)
      })
      .finally(() => {
        loading.value = false
      })
}

/** 加载医生列表 */
// 加载医生列表（如果是远程搜索场景，remote-method 会传 keyword ，这里接口不需要，所以可以忽略参数或者做兼容）
const loadDoctors = (keyword) => {
  doctorLoading.value = true
  getDoctorList()
      .then((response) => {
        if (response.code === 200) { // 假设你的接口返回有 code 、data 等字段，根据实际调整
          doctorOptions.value = response.data
        } else {
          ElMessage.error('加载医生列表失败，请重试')
        }
      })
      .catch((error) => {
        ElMessage.error('网络异常，请稍后再试')
        console.error('加载医生列表出错：', error)
      })
      .finally(() => {
        doctorLoading.value = false
      })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    appId: null,
    userId: null,
    doctorId: null,
    appInfo: null,
    appDateTime: null,
    appCreate: null,
    appStatse: null,
    appAddress: null
  }
  proxy?.resetForm("LXHDOCappointmentRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy?.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据（删除功能预留）
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.appId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 加载医生列表
  loadDoctors('')
  open.value = true
  title.value = "添加个人预约就诊"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _appId = row.appId || ids.value
  getLXHDOCappointment(_appId)
      .then(response => {
        form.value = response.data
        // 加载医生列表
        loadDoctors('')
        open.value = true
        title.value = "修改个人预约就诊"
      })
      .catch(error => {
        ElMessage.error("获取详情失败")
        console.error("详情查询错误:", error)
      })
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["LXHDOCappointmentRef"].validate(valid => {
    if (valid) {
      // // 自动填充当前用户ID（从框架获取，需框架支持）
      // form.value.userId = proxy.getUserId()
      // 自动填充提交时间（若需要）
      if (!form.value.appId) {
        form.value.appCreate = new Date()
      }

      const promise = form.value.appId
          ? updateLXHDOCappointment(form.value)
          : addLXHDOCappointment(form.value)

      promise.then(response => {
        ElMessage.success(form.value.appId ? "修改成功" : "新增成功")
        open.value = false
        getList()
      }).catch(error => {
        ElMessage.error(form.value.appId ? "修改失败" : "新增失败")
        console.error("提交错误:", error)
      })
    }
  })
}

/** 删除按钮操作（已注释按钮，保留方法逻辑） */
function handleDelete(row) {
  const _appIds = row.appId || ids.value
  ElMessageBox.confirm(`是否确认删除个人预约就诊编号为"${_appIds}"的数据项？`)
      .then(() => {
        return delLXHDOCappointment(_appIds)
      })
      .then(() => {
        getList()
        ElMessage.success("删除成功")
      })
      .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('LXHappointment/LXHDOCappointment/export', {
    ...queryParams.value
  }, `LXHDOCappointment_${new Date().getTime()}.xlsx`)
}

// 初始化加载数据
onMounted(() => {
  getList()
})
</script>